import React, { Component } from "react";
import { nanoid } from "nanoid";
import { connect } from "react-redux";
import { createAddPersonAction } from "../../redux/actions/person";

class Person extends Component {
  addPerson = () => {
    const name = this.nameNode.value;
    const age = this.ageNode.value*1;
    const personObj = { id: nanoid(), name, age };
    this.props.add(personObj)
    this.nameNode = ''
    this.ageNode = ''
  };

  render() {
    return (
      <div>
        <h2>Person组件, 上方组件求和为{this.props.count}</h2>
        <input
          ref={(c) => (this.nameNode = c)}
          type="text"
          placeholder="输入姓名"
        />
        <input
          ref={(c) => (this.ageNode = c)}
          type="text"
          placeholder="输入年龄"
        />
        <button onClick={this.addPerson}>add</button>
        <ul>
          {this.props.person.map((p) => {
            return (
              <li key={p.id}>
                {p.name}--{p.age}
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default connect((state) => ({ person: state.persons, count: state.count }), {
  add: createAddPersonAction,
})(Person);
